const CryptoJS = require('crypto-js')
const NodeRSA = require('node-rsa');
const crypto = require('crypto');

function random_t() {
    return (65536 * (1 + Math.random()) | 0).toString(16).substring(1);
}

function four_random_rt() {
    return random_t() + random_t() + random_t() + random_t();
}

function aesV(o_text, random_str) {
    var key = CryptoJS.enc.Utf8.parse(random_str);
    var iv = CryptoJS.enc.Utf8.parse("0000000000000000");
    var srcs = CryptoJS.enc.Utf8.parse(o_text);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        iv: iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    for (var r = encrypted, o = r.ciphertext.words, i = r.ciphertext.sigBytes, s = [], a = 0; a < i; a++) {
        var c = o[a >>> 2] >>> 24 - a % 4 * 8 & 255;
        s.push(c);
    }
    return s;
};

function arrayToHex(e) {
    for (var t = [], s = 0, n = 0; n < 2 * e.length; n += 2)
        t[n >>> 3] |= parseInt(e[s], 10) << 24 - n % 8 * 4,
            s++;
    for (var i = [], r = 0; r < e.length; r++) {
        var o = t[r >>> 2] >>> 24 - r % 4 * 8 & 255;
        i.push((o >>> 4).toString(16)),
            i.push((15 & o).toString(16));
    }
    return i.join("");
}


function genRSAesKey(data) {
    const public_key_1 = '00C1E3934D1614465B33053E7F48EE4EC87B14B95EF88947713D25EECBFF7E74C7977D02DC1D9451F79DD5D1C10C29ACB6A9B4D6FB7D0A0279B6719E1772565F09AF627715919221AEF91899CAE08C0D686D748B20A3603BE2318CA6BC2B59706592A9219D0BF05C9F65023A21D2330807252AE0066D59CEEFA5F2748EA80BAB81';
    const public_key_2 = '10001';
    const public_key = new NodeRSA();
    public_key.importKey({
        n: Buffer.from(public_key_1, 'hex'),
        e: parseInt(public_key_2, 16),
    }, 'components-public');
    const encrypted = crypto.publicEncrypt({
        key: public_key.exportKey('public'),
        padding: crypto.constants.RSA_PKCS1_PADDING
    }, Buffer.from(data));
    return encrypted.toString('hex');
}

var powSignFunc = function (e, t, s, n, i, r, o, guid) {
    var guid = four_random_rt();
    var a = i % 4;
    var _ = parseInt(i / 4, 10)
    var u = function g(e, t) {
        return new Array(t + 1).join(e);
    }('0', _);

    var c = n + '|' + i + '|' + s + '|' + r + '|' + t + '|' + e + '|' + o + '|';

    while (1) {
        var h = guid;
        var p = c + h;
        var l = void 0;
        // console.log(p);
        switch (s) {
            case 'md5':
                l = CryptoJS.MD5(p).toString();
                break;
            case 'sha1':
                l = CryptoJS.SHA1(p).toString();
                break;
            case 'sha256':
                l = CryptoJS.SHA256(p).toString();
        }
        if (0 == a) {
            if (0 === l.indexOf(u))
                return {"pow_msg": c + h, "pow_sign": l};
        } else if (0 === l.indexOf(u)) {
            var f = void 0
                , d = l[_];
            switch (a) {
                case 1:
                    f = 7;
                    break;
                case 2:
                    f = 3;
                    break;
                case 3:
                    f = 1;
            }
            if (d <= f)
                return {"pow_msg": c + h, "pow_sign": l};
        }
    }
}

// fullpage
function genFullW4(captchaId, lot_number, pow_detail) {
    var randomKey = four_random_rt();
    var {
        pow_msg,
        pow_sign
    } = powSignFunc(lot_number, captchaId,
        pow_detail.hashfunc, pow_detail.version, pow_detail.bits, pow_detail.datetime, '', randomKey)

    var ee = {
        "device_id": "",  //  66b8e216d2df1e07fd0fb495bc0a40c5
        "lot_number": lot_number,  // 接口返回
        "pow_msg": pow_msg,
        "pow_sign": pow_sign,
        "geetest": "captcha",
        "lang": "zh",
        "ep": "123",
        "biht": "1426265548", //  Fmhz(GErG.toString() + Fmhz.toString() +'')
        "x1HJ": "8FFD", //   "\u0078\u0031\u0048\u004a": $_CBHi(98)
        "em": {"ph": 0, "cp": 0, "ek": "11", "wd": 1, "nt": 0, "si": 0, "sc": 0}
    }

    var rsaVal = genRSAesKey(randomKey);

    var aesArray = aesV(JSON.stringify(ee), randomKey);
    var aesVal = arrayToHex(aesArray)

    var w = aesVal + rsaVal;
    return w

}

//slide
function genClickW4(captchaId, lot_number, passtime, pow_detail, userresponse) {
    var randomKey = four_random_rt();
    var {
        pow_msg,
        pow_sign
    } = powSignFunc(lot_number, captchaId,
        pow_detail.hashfunc, pow_detail.version, pow_detail.bits, pow_detail.datetime, '', randomKey)
    var ee = {
        "passtime": passtime, // 3807 滑动时间
        "userresponse": userresponse,  // [[4128, 7325], [4993, 2933]],
        "device_id": "",
        "lot_number": lot_number,
        "pow_msg": pow_msg,
        "pow_sign": pow_sign,
        "geetest": "captcha",
        "lang": "zh",
        "ep": "123",
        "biht": "1426265548", //  Fmhz(GErG.toString() + Fmhz.toString() +'')
        "x1HJ": "8FFD", //   "\u0078\u0031\u0048\u004a": $_CBHi(98)
        "em": {"ph": 0, "cp": 0, "ek": "11", "wd": 1, "nt": 0, "si": 0, "sc": 0}
    }

    var rsaVal = genRSAesKey(randomKey);

    var aesArray = aesV(JSON.stringify(ee), randomKey);
    var aesVal = arrayToHex(aesArray)

    var w = aesVal + rsaVal;
    return w
}


//slide
function genSlideW4(captchaId, lot_number, distance, passtime, pow_detail) {
    var randomKey = four_random_rt();
    // var randomKey = "130955df05531eae";
    var {
        pow_msg,
        pow_sign
    } = powSignFunc(lot_number, captchaId,
        pow_detail.hashfunc, pow_detail.version, pow_detail.bits, pow_detail.datetime, '', randomKey)
    // {"wrap_w": 300, "width": 80, "height": 80, "top": 29}
    var ee = {
        "setLeft": distance, // 176 滑动距离
        "passtime": passtime, // 1245 滑动时间
        "userresponse": distance / 1.0059466666666665 + 2, //176.95957373485675,  (0.8876 * 340 / 300)
        "device_id": "",
        "lot_number": lot_number,  // 接口返回

        "pow_msg": pow_msg,
        "pow_sign": pow_sign,
        "geetest": "captcha",
        "lang": "zh",
        "ep": "123",
        "biht": "1426265548", //  Fmhz(GErG.toString() + Fmhz.toString() +'')
        "x1HJ": "8FFD", //   "\u0078\u0031\u0048\u004a": $_CBHi(98)
        "em": {
            "ph": 0, "cp": 0, "ek": "11", "wd": 1, "nt": 0, "si": 0, "sc": 0
        }
    }

    var rsaVal = genRSAesKey(randomKey);

    var aesArray = aesV(JSON.stringify(ee), randomKey);
    var aesVal = arrayToHex(aesArray)

    var w = aesVal + rsaVal;
    return w
}


// var captchaId = '24f56dc13c40dc4a02fd0318567caef5',
//     lot_number = '8da9a8421dd44f3ca881d79e33518194',
//     distance = 220,
//     passtime = 12431;
//
// var pow_detail = {
//     'version': '1',
//     'bits': 0,
//     'datetime': '2024-02-03T16:28:05.378686+08:00',
//     'hashfunc': 'md5'
// }
//
// var result = genSlideW4(captchaId, lot_number, distance, passtime, pow_detail)
// console.log(result)